Skip to content

Add SendBatch to send several messages over one connection - #33

Merged
umputun merged 9 commits into
masterfrom
batch-send
Nov 17, 2026
Merged

umputun merged 9 commits into
masterfrom
batch-send

Conversation

@paskal

@paskal paskal commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Previously, Send ended the SMTP session after each message, including when a client was supplied through the SMTP option. After this change, SendBatch reuses one connection, authenticating once when credentials are configured and sending each valid message in its own transaction. The connection is used for one call, with no persistent pool.

After a rejection by the server, SendBatch continues only if RSET succeeds. RSET is used when the client has a Reset() error method, as smtp.Client does; SMTPClient is unchanged, so existing implementations and mocks keep compiling. A custom client without that method stops the batch at the first message the server rejects. A failed reset, a connection failure or a cancelled or expired context stops the rest of the batch. A done context closes a connection SendBatch opened, failing the message in flight, while a client from the SMTP option finishes its current message; a message that fails this way is reported with the context error, and may have been delivered all the same. BatchError reports the result of every message, and errors.Is and errors.As look into it on every supported Go version. Any other error means the session could not be set up and nothing was sent.

SendContext behaves as before; its authentication, transaction and QUIT steps moved into helpers it shares with SendBatch.

The PR also sets the token permissions of the CI workflow, the only workflow in the repository, to contents: read. The workflow set none, so the token had the repository default, which on master meant write access to contents, issues, pull requests, packages, pages, statuses, checks and security events, among others. The job checks out, builds, tests, lints and sends coverage to Coveralls, and writes nothing to GitHub, so the token now reads the repository contents and metadata only; every CI step passes with it, the Coveralls upload included. This resolves the CodeQL missing-workflow-permissions alert once merged. The PR also replaces interface{} with its alias any.

The tests run a batch against a fake SMTP server that refuses a nested MAIL, so the test fails without RSET, and against one that receives a message and never answers it, where the test cancels the context. The reset, broken connection, cancellation and session setup paths are also covered with the mock client. The suite passes with Go 1.19, the version in go.mod that CI uses, and with Go 1.27.

Resolves #7.

The workflow set no permissions, so the job inherited the repository's
token permissions, which can include write access. Set contents: read
explicitly to prevent inherited write access and address the CodeQL
actions/missing-workflow-permissions warning.
any is an alias of interface{}, so existing Logger implementations and
the generated mocks stay compatible.
Previously, Send ended the SMTP session after each message, including
when a client was supplied through the SMTP option, so a batch of
emails meant one session per message.

SendBatch reuses one connection, authenticating once when credentials
are configured and sending each valid message in its own transaction.
After a rejection by the server it continues only if RSET succeeds.
RSET comes from the new single-method SMTPResetter interface, which
smtp.Client implements; SMTPClient is unchanged, so existing
implementations keep compiling. A failed or unavailable reset, a
connection failure or a cancelled or expired context stops the rest
of the batch. BatchError reports the result of every message, and its
Is and As methods let errors.Is and errors.As look into it on Go 1.19,
which does not follow a multi-error Unwrap.

The authentication, transaction and QUIT steps of SendContext move
into helpers shared with SendBatch, without a change in its behaviour.
@paskal
paskal requested a review from umputun as a code owner November 7, 2026 13:19

@umputun umputun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a few small things before merge:

  • email.go:262-282 - if ctx is cancelled while a message is in flight on a connection SendBatch opened itself, the ctx watcher closes the connection. That message then fails with "bad from address ...: use of closed network connection", the rest get the same error, and errors.Is(err, context.Canceled) is false. The same cancel between two messages gives context.Canceled. Fix: after a failure, check ctx.Err() before reset and wrap it for this message and the rest (below). Also add a test with a server that stalls mid-message; the current cancel test uses an injected client, so it covers only a cancel between messages:
if cerr := ctx.Err(); cerr != nil {
	errs[i] = fmt.Errorf("%w: %v", cerr, err)
	fillUnsent(errs[i+1:], cerr)
	break
}
  • email.go:88, email.go:220, README.md:75, README.md:86 - failed entries are called "not sent". When the connection drops after the server got the message body, the message may already be delivered, so a caller who retries the "not sent" entries delivers it twice. Fix: say "failed" in these places. The entries after a broken session were never attempted, so their "not sent" text is right.
  • README.md:74-75 - "a message the server rejects doesn't stop the batch" holds only for a client with Reset(). A custom SMTP client without it stops at the first rejection. Fix: add a clause about it. The godoc at email.go:77 is off the other way: "stops at the first failure" should be "stops at the first message the server rejects", because a message rejected before sending doesn't stop it.
  • README.md:82-89 - the example handles only *BatchError. If someone copies it as is, a dial or auth error, where nothing was sent, is silently dropped. Fix: return any other error before the loop.
  • email.go:76 - SMTPResetter is only used in the type assertion, and a custom client needs nothing more than a Reset() error method. Pls make it unexported and name that method in the SendBatch godoc. That keeps the public API smaller.
  • email.go:325 - fillUnsent is called only from SendBatch, pls make it a method on Sender.
  • batch_test.go:100-111 - pls generate the Reset mock with moq, like the other mocks, in place of the hand-written method. With an unexported interface, moq -out mocks/resetter.go -pkg mocks -skip-ensure -fmt goimports . resetter:ResetterMock still gives an exported mock. Add the //go:generate line next to the existing ones, and embed both mocks in the test client.
  • the comments in batch_test.go (lines 24, 40, 84, 100, 141, 235) and on sendMessage, authenticate and transaction mostly repeat what the code says, pls drop them.

Previously, cancelling the context while a message was in flight on a
connection SendBatch had opened closed that connection, and the
message and the rest of the batch failed with a closed network
connection error that did not match context.Canceled. A deadline
could do the same through the connection deadline, which is set to
the context's and can fire before ctx.Err reports it.

Now a transaction failure after the context is done or its deadline
has passed is reported with the context error, keeping the SMTP error
text, and the rest of the batch gets the context error, as with a
cancellation between messages.
SendBatch only type-asserts the client to it, and a custom client
needs nothing more than a Reset() error method, so the interface does
not belong in the public API; the SendBatch documentation names the
method and says the batch stops at the first message the server
rejects without it.

The test client embeds the moq-generated ResetterMock next to
SMTPClientMock in place of a hand-written Reset method, fillUnsent
becomes a method of Sender, and comments that repeat the code are
gone.
A message whose connection drops after the server got its body may
already be delivered, so calling it not sent invites a retry that
delivers it twice. Messages after a broken session are never
attempted and keep "not sent".

The README documents that a custom client without a Reset() error
method stops the batch at the first message the server rejects, and
its example returns errors other than BatchError, where nothing was
sent, before looking at the failed messages.
A message the server rejected just as the context was cancelled or
its deadline passed was reported with the context error, preserving
the reply only as text and hiding its *textproto.Error from
errors.As. The context error is now applied to that message only when
the failure is not a server reply; the rest of the batch still gets
the context error.
@paskal

paskal commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks a lot for the review. All eight points are addressed in the last four commits.

After a failed transaction, SendBatch checks the context before reset, as in your snippet. If the context has ended, a server rejection stays as it is, other failures wrap the context error and keep the SMTP error text, and the remaining messages get the context error. The check also treats an expired deadline as done before ctx.Err() is set, so a plain i/o timeout from the connection deadline, which is the same as the context's, doesn't come back in its place. TestEmail_SendBatchCanceledInFlight runs against a server that receives the message and never answers the end of DATA, with a cancel and with a deadline, and checks errors.Is for the context error on the batch error and on both messages.

The rest is as you asked:

  • "failed" in place of "not sent" in the BatchError comment, the SendBatch godoc and the README; only the entries after a broken session keep "not sent".
  • The README and the SendBatch godoc say that a custom SMTP client without a Reset() error method stops the batch at the first message the server rejects.
  • The README example returns any error other than *email.BatchError before the loop.
  • SMTPResetter is the unexported resetter, fillUnsent is a method of Sender, mocks/resetter.go comes from the //go:generate line you suggested, and the test client embeds both mocks.
  • The listed comments are removed.

@paskal
paskal requested a review from umputun November 8, 2026 08:30

@umputun umputun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

last round's items check out, two small things left:

  • email.go:287 - the in-flight fix doesn't cover RSET. If ctx is cancelled or its deadline passes while RSET after a rejection is still waiting for the server, the watcher closes the connection and Reset() fails with "use of closed network connection" (or an i/o timeout for a deadline). The rest of the batch get that error, so errors.Is(err, context.Canceled) is false again (context.DeadlineExceeded for a deadline), same as last round's first point. Fix: check ctxDone when reset fails and keep errs[i] as the server reply. Pls add a test for it too: 550 on RCPT, then ctx ends during RSET, either with a stalled server or with a ResetFunc that cancels ctx and returns a plain error like errors.New("connection closed") (not context.Canceled, it would pass without the fix):
if rerr := em.reset(client, err); rerr != nil {
	if cerr := ctxDone(ctx); cerr != nil {
		rerr = fmt.Errorf("%w: %v", cerr, rerr)
	}
	em.fillUnsent(errs[i+1:], fmt.Errorf("not sent, the session ended after message %d failed: %w", i, rerr))
	break
}
  • batch_test.go:316 - pls drop "the message is received and never answered", it's the same kind of comment as the ones removed last round.

When the context ended during RSET after a server rejection, the
remaining messages got a connection error that hid the context error.
A failed reset now wraps the context error when the context is done,
keeping the reset error as text. The rejected message keeps the
server reply.
@paskal

paskal commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks a lot, both are addressed in the last two commits:

  • After a failed reset, SendBatch checks ctxDone as in your snippet. The remaining messages wrap the context error and keep the reset error as text; the rejected message keeps the server reply. The new test ends the context during reset after a 550 on RCPT, with a cancel and with a passed deadline, and fails without the fix.
  • The comment in TestEmail_SendBatchCanceledInFlight is removed.

@paskal
paskal requested a review from umputun November 8, 2026 09:16

@umputun umputun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@umputun
umputun merged commit 54ad448 into master Nov 17, 2026
6 of 8 checks passed
@umputun
umputun deleted the batch-send branch November 17, 2026 07:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Connections pool

2 participants